package com.tledu.dangjian.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.tledu.dangjian.core.exception.UsernameRepeatException;
import com.tledu.dangjian.dao.UserDao;
import com.tledu.dangjian.model.Role;
import com.tledu.dangjian.model.User;
import com.tledu.dangjian.service.IUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author cyrus
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User, UserDao> implements IUserService {
    /**
     * 注入依赖
     *
     * @param userDao 注入userDao的依赖
     */
    public UserServiceImpl(UserDao userDao) {
        super(userDao);
    }

    @Override
    public User login(String username, String password) {
        return baseDao.login(username, password);
    }

    @Override
    @Transactional(rollbackFor = Exception.class, isolation = Isolation.SERIALIZABLE)
    public Integer insert(User entity) {
        // 对密码进行加密
        entity.setPassword(SecureUtil.md5("111111"));
        // 校验用户名是否唯一
        int count = baseDao.countByUserName(entity.getUsername());
        if (count > 0) {
            // 有用户名冲突
            throw new UsernameRepeatException("用户名重复");
        }
        // 建立关联关系
        List<Integer> roleIdList = new ArrayList<>();
        for (Role role : entity.getRoleList()) {
            roleIdList.add(role.getRoleId());
        }
        // 获取当前插入用户的id
        Integer num = baseDao.insert(entity);
        baseDao.addRoles(roleIdList, entity.getUserId());
        return num;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int update(User entity) {
        // 建立关联关系
        List<Integer> roleIdList = new ArrayList<>();
        for (Role role : entity.getRoleList()) {
            roleIdList.add(role.getRoleId());
        }
        // 获取当前插入用户的id
        baseDao.clearRole(entity.getUserId());
        baseDao.addRoles(roleIdList, entity.getUserId());
        return baseDao.update(entity);
    }
}
